//
//  CityFieldTableViewController.swift
//  GoTravel
//
//  Created by lanou3g on 16/3/12.
//  Copyright © 2016年 SHH. All rights reserved.
//

import UIKit

class CityFieldTableViewController: UITableViewController {
    
    var urlArray:NSArray?
    
    var url:String?
    var page:Int?
    var dataArray:NSMutableArray?
    var placesUrl:String?
    
    override func viewWillAppear(animated: Bool) {
        SHHGetData.sharedGetData.cityDetailArray.removeAll()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //注册cell
        self.tableView.registerNib(UINib(nibName: "CityDetailTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        
//        SHHGetData.sharedGetData.cityDetailArray.removeAll()
        self.dataArray = NSMutableArray()
        
        self.loadNewData()
        
        //MJ刷新
        //顶部刷新
        let header = MJRefreshNormalHeader()
        //底部刷新
        let footer = MJRefreshAutoNormalFooter()
        header.setRefreshingTarget(self, refreshingAction: Selector("headerRefresh"))
        self.tableView.mj_header = header
        
        //上拉刷新
        footer.setRefreshingTarget(self, refreshingAction: Selector("footerRefresh"))
        self.tableView.mj_footer = footer
        
    }
    
    //下拉刷新
    func headerRefresh() {
        print("下拉刷新")
        self.loadNewData()
        //结束刷新
        self.tableView.mj_header.endRefreshing()
    }
    
    //底部刷新
    func footerRefresh() {
        print("上拉刷新")
        self.loadMoreData()
        self.tableView.mj_footer.endRefreshing()
    }
    
    
    //请求数据
    func requestUrl() {
        let string = String(self.page!)
        if self.urlArray![0] as! NSObject == 0 {
            self.url = "http://www.koubeilvxing.com/search?lat=0.000000&lng=0.000000&module=attraction&page=" +  string + "&placeId=" + (self.urlArray![1] as! String) + "&rows=10"
        }else if self.urlArray![0] as! NSObject == 1 {
            self.url = "http://www.koubeilvxing.com/search?lat=0.000000&lng=0.000000&module=restaurant&page=" +  string + "&placeId=" + (self.urlArray![1] as! String) + "&rows=10"
        }else if self.urlArray![0] as! NSObject == 2 {
            self.url = "http://www.koubeilvxing.com/search?lat=0.000000&lng=0.000000&module=hotel&page=" +  string + "&placeId=" + (self.urlArray![1] as! String) + "&rows=10"
        }else if self.urlArray![0] as! NSObject == 3 {
            self.url = "http://www.koubeilvxing.com/search?lat=0.000000&lng=0.000000&module=shopping&page=" +  string + "&placeId=" + (self.urlArray![1] as! String) + "&rows=10"
        }else {
            self.url = "http://www.koubeilvxing.com/search?lat=0.000000&lng=0.000000&module=activity&page=" +  string + "&placeId=" + (self.urlArray![1] as! String) + "&rows=10"
        }
        print("++++++++++\(self.url!)")
        
        self.setUpDataWithString(self.url!)
    }
    
    func loadNewData() {
        self.page = 1
        self.requestUrl()
        //刷新表格
        self.tableView.reloadData()
    }
    
    func loadMoreData() {
        self.page!++
        self.requestUrl()
        self.tableView.reloadData()
    }
    
    func setUpDataWithString(string:String) {
        let url = NSURL(string: string)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
            
            do{
                let dic = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                let array = dic["list"] as! NSArray
                for dict in array {
                    let model = CityDetailModel()
                    model.setValuesForKeysWithDictionary(dict as! [String : AnyObject])
                    self.dataArray?.addObject(model)
                }
                
            }catch{
                
            }
            
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.tableView.reloadData()
            })
        })
        task.resume()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
//        return SHHGetData.sharedGetData.cityDetailArray.count
        return (self.dataArray?.count)!
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UIScreen.mainScreen().bounds.height / 2.4
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? CityDetailTableViewCell
        
//        let model = SHHGetData.sharedGetData.cityDetailArray[indexPath.row]
        let model:CityDetailModel = self.dataArray![indexPath.row] as! CityDetailModel
        let urlString = "http://img.koubeilvxing.com/pics" + model.path!
        cell?.picImageView.sd_setImageWithURL(NSURL(string: urlString))
        cell?.name_cnLabel.text = model.name_cn!
        cell?.nameLabel.text = model.name!
        let score = model.score! + "/" + model.reviewCount!
        cell?.scoreLabel.text = score
        return cell!
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
<<<<<<< HEAD
        
        
        
=======
        let placeVC = CityDetailShowVC()
//        let model:CityDetailModel = self.dataArray![indexPath.row] as! CityDetailModel
        self.getPlacesUrl(indexPath)
        placeVC.url = self.placesUrl
        print("========\(self.placesUrl)")
        self.presentViewController(placeVC, animated: true, completion: nil)
>>>>>>> 7b0b9e42f2654a64617728d21e1fd5c58cf003fc
    }

    
    //请求数据
    func getPlacesUrl(indexPath:NSIndexPath) {
        let model:CityDetailModel = self.dataArray![indexPath.row] as! CityDetailModel
        let string:String = model.ID!
        if self.urlArray![0] as! NSObject == 0 {
            self.placesUrl = "http://www.koubeilvxing.com/iteminfo?module=attraction&recordId=" + string
        }else if self.urlArray![0] as! NSObject == 1 {
            self.placesUrl = "http://www.koubeilvxing.com/iteminfo?module=restaurant&recordId=" + string
        }else if self.urlArray![0] as! NSObject == 2 {
            self.placesUrl = "http://www.koubeilvxing.com/iteminfo?module=hotel&recordId=" + string
        }else if self.urlArray![0] as! NSObject == 3 {
            self.placesUrl = "http://www.koubeilvxing.com/iteminfo?module=shopping&recordId=" + string
        }else {
            self.placesUrl = "http://www.koubeilvxing.com/iteminfo?module=activity&recordId=" + string
        }
        print("++++++++++\(self.placesUrl)")
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
